package com.unibuy.smartdevice.ui.dialog;

import android.content.Context;

import com.unibuy.smartdevice.DialogAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.databinding.DialogInvoiceBarcodeBinding;
import com.unibuy.smartdevice.devices.DeviceType;
import com.unibuy.smartdevice.devices.UsbDev;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.exception.LogsIOException;
import com.unibuy.smartdevice.exception.LogsUnsupportedOperationException;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainCountdown;
import com.unibuy.smartdevice.tools.HandlerMainScheduler;
import com.unibuy.smartdevice.tools.ToastHandlerMain;

import java.util.HashMap;
import java.util.Map;

public class InvoiceBarcodeDialog extends DialogAbstract {
    public enum Option {
        TOAST(0),
        COUNTDOWN_CANCEL(1),
        SET_COUNTDOWN_TEXT(2),
        INVOICE_SUCCESSFUL(4),
        INVOICE_FAILED(5),
        CHANGE_DISPATCH(6),
        CHANGE_BUY(7),
        CHANGE_CHECKOUT(8),
        ;

        private int option;

        public int getOption() {
            return option;
        }

        Option(int option) {
            this.option = option;
        }
    }

    public static final Map<Integer, Option> optionMap = new HashMap<>();
    static {
        for (Option option : Option.values()) {
            optionMap.put(option.getOption(), option);
        }
    }

    @Override
    protected Context setCtx() {
        return getContext();
    }

    @Override
    protected Class<? extends DialogAbstract> setCls() {
        return getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                if (MyApp.getInstance().getBuyList().size() <= 0) {

                    dialogCancel();
                } else {
                    Option option = optionMap.get(commandCode);
                    getLogs().info("Option " + option.getOption() + ":" + option.name());
                    switch (option) {
                        case TOAST:
                            super.execute(context, commandCode, message);
                            break;
                        case COUNTDOWN_CANCEL:
                            cancelOnThreadCountdown();
                            break;
                        case SET_COUNTDOWN_TEXT:
                            try {
                                setButtonCancelText(Integer.valueOf(message));
                            } catch (NumberFormatException e) {
                                return;
                            }
                            break;
                        case INVOICE_SUCCESSFUL:
                            //----- 發票載具 ------
                            binding.textInvoiceCarrier.setText(getContext().getString(R.string.vehicles)+":"+message);//載具
                            MyApp.getInstance().getInvoiceData().setCarrier(message);
                            MyApp.getInstance().getReportFlowInfoData().setInvoiceInfo("carrier:" + MyApp.getInstance().getInvoiceData().getCarrier());
                            new HandlerMainCountdown(this) {
                                @Override
                                protected Class<?> setCls() {
                                    return this.getClass();
                                }

                                @Override
                                protected HandlerMain setHandlerMain() {
                                    return getSrcHandlerMain();
                                }

                                @Override
                                protected void execute(long countdown, HandlerMain handlerMain) {

                                }

                                @Override
                                protected void close(HandlerMain handlerMain) {
                                    handlerMain.start(getSrcClassName(), Option.CHANGE_CHECKOUT.getOption(), "change dispatch");
                                }
                            }.start(2);
                            break;
                        case INVOICE_FAILED:
                            break;
                        case CHANGE_DISPATCH:
                            super.execute(context, commandCode, message);
                            changeDispatch();
                            break;
                        case CHANGE_BUY:
                            super.execute(context, commandCode, message);
                            changeBuy();
                            break;
                        case CHANGE_CHECKOUT:
                            super.execute(context, commandCode, message);
                            changeCheckout();
                            break;
                    }
                }
            }
        };
    }

    private DialogInvoiceBarcodeBinding binding;
    private CloseDialogOnThreadHandler closeDialogCountdown;
    private boolean openBarcode;
    private ReadBarCodeOnScheduler readBarCodeOnScheduler;

    public InvoiceBarcodeDialog(Context context, HandlerMain srcHandlerMain) {
        super(context, srcHandlerMain);
        openBarcode = true;
    }

    @Override
    protected void onCreate(Context context) {
        binding = DialogInvoiceBarcodeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.buttonCustomerIdentifier.setOnClickListener(v -> changeCustomerIdentifier());
        binding.buttonDonation.setOnClickListener(v -> changeDonation());
        binding.buttonCancel.setOnClickListener(v -> changeBuy());

        closeDialogCountdown = new CloseDialogOnThreadHandler(getHandlerMain());
        closeDialogCountdown.start(40);

        readBarCodeOnScheduler = new ReadBarCodeOnScheduler(getHandlerMain());
        readBarCodeOnScheduler.start();

        binding.imageCheckout.setOnClickListener(v -> changeDispatch());
    }

    public void changeDispatch() {
        closeDialogCountdown.shutdown();
//        DispatchDialog dispatchDialog = new DispatchDialog(getContext(), getSrcHandlerMain());
//        dispatchDialog.show();
        FlowerPickupDialog fLowerPickupDialog = new FlowerPickupDialog(getContext(), getSrcHandlerMain());
        fLowerPickupDialog.show();
        openBarcode = false;
        cancel();
    }

    public void changeCustomerIdentifier() {
        closeDialogCountdown.shutdown();
        new InvoiceCustomerIdentifierDialog(getCtx(), getSrcHandlerMain()).show();
        openBarcode = false;
        cancel();
    }

    public void changeDonation() {
        // 168001 OMG關懷社會愛心基金會
        MyApp.getInstance().getInvoiceData().setLoveCode("168001");
        MyApp.getInstance().getReportFlowInfoData().setInvoiceInfo(
                "loveCode:" + MyApp.getInstance().getInvoiceData().getLoveCode()
        );
        changeCheckout();
    }

    public void changeBuy() {
        closeDialogCountdown.shutdown();
        BuyDialog buyDialog = new BuyDialog(getContext(), getSrcHandlerMain());
        buyDialog.show();
        openBarcode = false;
        cancel();
    }

    public void changeCheckout() {
        closeDialogCountdown.shutdown();
        int flowType = MyApp.getInstance().getReportFlowInfoData().getFlowType();
        switch (flowType) {
            case 9:
                changeDialog(CheckoutCashDialog.class);
                break;
        }
        openBarcode = false;
        cancel();
    }

    public void dialogCancel() {
        readBarCodeOnScheduler.setRun(false);
        closeDialogCountdown.shutdown();
        MyApp.getInstance().getBuyList().clear();
        openBarcode = false;
        cancel();
    }

    public void cancelOnThreadCountdown() {
        MyApp.getInstance().getBuyList().clear();
        openBarcode = false;
        cancel();
    }

    public void setButtonCancelText(long countdown) {
        binding.buttonCancel.setText(getContext().getString(R.string.return_to)+"("+countdown+")");//返回
    }

    public class ReadBarCodeOnScheduler extends HandlerMainScheduler {
        public ReadBarCodeOnScheduler(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            try {
                UsbDev usbDev = new UsbDev(DeviceType.QRCODE_SCANNER);
                byte[] buffer = new byte[20];
                usbDev.read(buffer, 100);
                for (int i=0; i<7; i++) {
                    if (isRun() && openBarcode) {
                        int size = usbDev.read(buffer, 5000);
                        if (size > 5) {
                            String barCodeString = new String(buffer, 0, size);
                            handlerMain.start(getClass().getSimpleName(), Option.INVOICE_SUCCESSFUL.getOption(), barCodeString);
                            openBarcode = false;
                        }
                    }
                }
                usbDev.closePort();
            } catch (LogsUnsupportedOperationException | LogsIOException | LogsEmptyException e) {
                getLogs().warning(e);
            }
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    public static class CloseDialogOnThreadHandler extends HandlerMainCountdown {
        public CloseDialogOnThreadHandler(HandlerMain handlerMain) {
            super(handlerMain);
            handlerMain.start(getClass().getSimpleName(), CheckoutCashDialog.Option.SET_COUNTDOWN_TEXT.getOption(), String.valueOf(getSrcCountdown()));
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void close(HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.COUNTDOWN_CANCEL.getOption(), "close dialog");
        }

        @Override
        protected void execute(long countdown, HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.SET_COUNTDOWN_TEXT.getOption(), String.valueOf(countdown));
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }
}
